//
//  RTJImmediatelyLendController.m
//  RuiTaiJinProject
//
//  Created by jayson on 2018/12/3.
//  Copyright © 2018年 leewei. All rights reserved.
//

#import "RTJImmediatelyLendController.h"
#import "RTJLendCell.h"
#import "RTJLendResultController.h"
#import "RTJChargeController.h"
#import "RTJChargeRootController.h"
#import "RTJRiskAssessmentController.h"
#import "RTJForgetPassWordController.h"
#import "RTJBidRecordsRootController.h"
#import "RTJUseRrealNameController.h"
#import "RTJHBJXController.h"
#import "RTJJiaXiController.h"

@interface RTJImmediatelyLendController ()<UITextFieldDelegate,HongbaoDelegate,JiaXiDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)NSArray *hbList;
@property (nonatomic,strong)NSArray *jxList;
@property (nonatomic,strong) NSString *money;

@property (nonatomic,assign) NSInteger hongbao;
@property (nonatomic,strong) NSString *hongbaoName;
@property (nonatomic,strong) NSString* hongbaoId;
@property (nonatomic,assign) NSInteger hongbaoMin_money;
@property (nonatomic,strong) NSString* cardName;
@property (nonatomic,assign) NSInteger cardId;
@property (nonatomic,assign) NSInteger hongbao_money;


@property (nonatomic,assign) CGFloat jiaxi;
@property (nonatomic,strong) NSString *jiaxiName;
@property (nonatomic,strong) NSString *jiaxiId;
@property (nonatomic,assign) NSInteger jiaxiMin_money;
@property (nonatomic,strong) NSString *yuqishouyi;
@property (nonatomic,strong) NSString *payStr;

@property (nonatomic,strong) NSString *hongbaoStr;
@property (nonatomic,strong) NSString *jiaxiStr;
@property (nonatomic,strong) NSString *passwordStr;
@property (nonatomic,strong) NSString *markpasswordStr;

@property (nonatomic,assign) BOOL isSurePay;
@property (nonatomic,assign) NSInteger is_encryption;

@property (nonatomic,assign) BOOL isSelected;



@end

@implementation RTJImmediatelyLendController

-(void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = NO;
    self.view.userInteractionEnabled = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];


    self.title = @"立即出借";
    self.tableView.tableFooterView=[UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.estimatedRowHeight=300;
    
    _isSelected = YES;
    _jiaxi = 0;
    _hongbao = 0;
    
    [self loadData];
}

-(void)loadData{
    
    
    [SVProgressHUD  showWithStatus:nil];
    [self.view showEmptyViewWithStr:@"" image:nil callback:nil];
    
    [RTJNetWork asyncRequestWithURL:@"deals/bid" params:@{@"id":_idStr} method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [self.view removeEmptyView];
        [SVProgressHUD dismiss];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                self.is_encryption = [data[@"data"][@"deal_info"][@"is_encryption"] integerValue];
                self.hbList = data[@"data"][@"ecv_list"];
                self.jxList = data[@"data"][@"interestrate_list"];
                [self.tableView reloadData];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
                [self.view showEmptyViewWithStr:data[@"msg"] image:[UIImage imageNamed:@"kbylogo"] callback:^{
                    [self loadData];
                }];
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            [self.view showEmptyViewWithStr:errorMsg image:[UIImage imageNamed:@"kbylogo"] callback:^{
                [self loadData];
            }];
        }
                
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewAutomaticDimension;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * ID = @"RTJLendCell";
    
    RTJLendCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (!cell) {
            
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJLendCell" owner:self options:nil][0];
        }
    
    if (_max_mon == 0) {
        
        cell.qitouzijin.text = [NSString stringWithFormat:@"%ld元起投",(long)_min_mon];
//        cell.qitouzijin.text = @"";

    }else{
        
        cell.qitouzijin.text = [NSString stringWithFormat:@"投资上限金额%ld元",(long)_max_mon];

    }
    
    cell.sub_name.text = _titleStr;
    cell.time_type.text = _time_typeStr;
    cell.timeLab.text = _timeStr;
    cell.rate.text = _rateStr;
    cell.texFld.delegate = self;
    cell.texFld.tag = 100;
    cell.pswFld.delegate = self;
    cell.pswFld.tag = 200;
    cell.pswFld.text = _markpasswordStr;
    cell.fldHeight.constant =  self.is_encryption == 1 ? 50 :0;
    cell.pswFld.hidden =  self.is_encryption == 1 ? NO :YES;


    cell.texFld.text = _money;
    cell.texFld.placeholder = [NSString stringWithFormat:@"%ld元起投",(long)_min_mon];
    cell.remainLab.text = [NSString stringWithFormat:@"%@元",_remainStr];
    cell.remainMoneyLab.text  = [NSString stringWithFormat:@"可用金额: %@",[RTJUserTool getTheUserModel].money_format];
    cell.shouyiLab.text = _yuqishouyi.length!=0 ? [NSString stringWithFormat:@"%@ 元",_yuqishouyi] :@"0元";
    cell.payLab.text = _payStr.length!=0 ? [NSString stringWithFormat:@"%@ 元",_payStr] :@"0元";
    
    if (_rebateStr.length == 0) {
        
        cell.rebateLab.hidden = YES;
        
    }else{
        
        cell.rebateLab.hidden = NO;
        NSString *str = @"%";
        cell.rebateLab.text = [NSString stringWithFormat:@"+%@%@",_rebateStr,str];
    }
    
    cell.hongbaoBtn.userInteractionEnabled = _hbList.count!=0 ? YES : NO;
    cell.jiaxiBtn.userInteractionEnabled = _jxList.count!=0 ? YES : NO;
    [cell.hongbaoBtn addTarget:self action:@selector(hongbaoBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.hongbaoBtn.tag = 100;
    [cell.jiaxiBtn addTarget:self action:@selector(hongbaoBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.chozhiBtn addTarget:self action:@selector(chongzhiBtn) forControlEvents:UIControlEventTouchUpInside];

    cell.hongbaoLab.text = _hbList.count!=0 ? (_hongbaoName.length!=0 ?_hongbaoName : [NSString stringWithFormat:@"有%lu张可用的红包",(unsigned long)_hbList.count]):@"暂无可用的红包";
    cell.jiaxiLab.text = _jxList.count!=0 ? (_jiaxiName.length!=0 ? _jiaxiName :[NSString stringWithFormat:@"有%lu张可用的加息券",(unsigned long)_jxList.count]) : @"暂无可用的加息券";
    cell.selectedBtn.selected = _isSelected;
    [cell.selectedBtn addTarget:self action:@selector(selectedBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.xieyiBtn1 addTarget:self action:@selector(xieyi) forControlEvents:UIControlEventTouchUpInside];
    [cell.xieyiBtn2 addTarget:self action:@selector(xieyi1) forControlEvents:UIControlEventTouchUpInside];
    [cell.xieyiBtn3 addTarget:self action:@selector(xieyi2) forControlEvents:UIControlEventTouchUpInside];

    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return  cell;
    
}


-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (textField.tag == 100) {
        
        _money = textField.text;
        
        NSInteger shuruMoney = [_money integerValue];
        
        if (shuruMoney< _min_mon) {
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%ld元起投,请重新输入金额",(long)_min_mon]];
            _hongbaoName = @"";
            _hongbao = 0;
            _hongbaoId = @"";
            _isSurePay = YES;
            
            CGFloat rete = [_rateStr floatValue];
            CGFloat rebate1 = [_rebateStr floatValue];//加息
            CGFloat repay_time = [_timeStr floatValue];
            
            CGFloat shouyi = shuruMoney*((rete+_jiaxi+rebate1)/100/12)*repay_time;
            
            _yuqishouyi = [NSString stringWithFormat:@"%.2f",shouyi];
            
            //实际支付
            _payStr = [NSString stringWithFormat:@"%ld",shuruMoney-_hongbao];
            
            [self.tableView reloadData];
            
            return;
            
            
        }else if (shuruMoney>_max_mon&& _max_mon!=0){
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"超过投资上限%ld元,请重新输入金额",(long)_max_mon]];
            _hongbaoName = @"";
            _hongbao = 0;
            _hongbaoId = @"";
            _isSurePay = YES;
            
            CGFloat rete = [_rateStr floatValue];
            CGFloat rebate1 = [_rebateStr floatValue];//加息
            CGFloat repay_time = [_timeStr floatValue];
            
            CGFloat shouyi = shuruMoney*((rete+_jiaxi+rebate1)/100/12)*repay_time;
            
            _yuqishouyi = [NSString stringWithFormat:@"%.2f",shouyi];
            
            //实际支付
            _payStr = [NSString stringWithFormat:@"%ld",shuruMoney-_hongbao];
            
            [self.tableView reloadData];
            
            return;
            
        }else{
            
            //账户剩余的钱
            NSInteger money = [[RTJUserTool getTheUserModel].money integerValue];

            if (shuruMoney>money) {

                [SVProgressHUD showErrorWithStatus:@"账户余额不足，请前往充值"];
                _isSurePay = YES;
                return;
            }
            
            //剩余可以投的钱
            NSString *str = [_remainStr stringByReplacingOccurrencesOfString:@"," withString:@""];

            NSInteger ramainmoeney = [str integerValue];
            
            if (shuruMoney>ramainmoeney) {
                
                [SVProgressHUD showErrorWithStatus:@"输入的金额超过可投资金额"];
                _isSurePay = YES;
                return;
            }
            
            //预期收益
            //收益 = 投标金额*（预期年化*/100/12）*投资期限
            CGFloat rebate1 = [_rebateStr floatValue];//加息
            
            CGFloat rete = [_rateStr floatValue];
            
            CGFloat repay_time = [_timeStr floatValue];
            
            CGFloat shouyi = shuruMoney*((rete+_jiaxi+rebate1)/100/12)*repay_time;
            
            _yuqishouyi = [NSString stringWithFormat:@"%.2f",shouyi];
            
            //实际支付
            _payStr = [NSString stringWithFormat:@"%ld",shuruMoney-_hongbao];
            
            _isSurePay = NO;
            
            [self.tableView reloadData];
            
        }
        
        if (_hongbaoMin_money !=0) {
            
            [self hongBaoName:_cardName money:_hongbao_money cardId:_cardId min_money:_hongbaoMin_money];
        }

    }else{
        
        _markpasswordStr = textField.text;
    }
    
    
    
}

-(void)selectedBtn:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    
    _isSelected = btn.selected;
}


- (IBAction)lendOut:(id)sender {
    
    if (_isSelected == NO) {
        
        [SVProgressHUD showErrorWithStatus:@"请仔细阅读相关协议"];
        return;
    }
    
    if (self.is_encryption == 1) {
        
        if (_markpasswordStr.length==0) {
            
            [SVProgressHUD showErrorWithStatus:@"请输入约标密码"];
            return;
        }
        
    }
    
    if (_money.length==0) {
        
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%ld元起投,请输入金额",(long)_min_mon]];
        return;
    }
    
    NSInteger mon = [_money integerValue];
    if (mon > [[RTJUserTool getTheUserModel].money integerValue]) {
        
        [SVProgressHUD showErrorWithStatus:@"账户余额不足，请前往充值"];
        return;
    }
    
    if ([RTJUserTool getTheUserModel].idcardpassed == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"你还没有进行实名认证，请前往认证"];
        
        RTJUseRrealNameController *vc = [[RTJUseRrealNameController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    
    
    if ([RTJUserTool getTheUserModel].is_risk == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"你还没有进行风险评测，请前往测评"];
        
        RTJRiskAssessmentController *risk =  [[RTJRiskAssessmentController alloc]init];
        [self.navigationController pushViewController:risk animated:YES];
        return;
        
    }
    
    NSString *paypassword = [RTJUserTool getTheUserModel].paypassword;
    
    if ( paypassword.length ==0) {
        
        [SVProgressHUD showErrorWithStatus:@"你还没有设置交易密码，请前往设置"];
        RTJForgetPassWordController *vc = [[RTJForgetPassWordController alloc]init];
        vc.title = @"设置支付密码";
        vc.isPayPassWord = YES;
        vc.isForgetPassWord = NO;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;

    }
    
        SpecialAlertView *special = [[SpecialAlertView alloc]initWithLevelType:YES];

        [special withSureClick:^(NSInteger tags,NSString *password,UIView *alertView) {

            [UIView animateWithDuration:0.3 animations:^{
                [alertView removeFromSuperview];
            }];
            
            if (tags == 110) {

//                [UIView animateWithDuration:0.3 animations:^{
//                    [alertView removeFromSuperview];
//                }];

                RTJForgetPassWordController *vc = [[RTJForgetPassWordController alloc]init];
                vc.isPayPassWord = YES;
                vc.title = @"找回支付密码";
                [self.navigationController pushViewController:vc animated:YES];

            }else{

                if (password.length  == 0) {

                    [SVProgressHUD showErrorWithStatus:@"请输入交易密码"];
                    return ;
                }
                self.passwordStr = password;
                //验证支付密码是否正确
                [RTJNetWork asyncRequestWithURL:@"user/check_pay_password" params:@{@"pay_password":password} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {

                    if (success) {
                        
                        if ([data[@"status"]integerValue]==1) {
                            
//                            [UIView animateWithDuration:0.3 animations:^{
//                                [alertView removeFromSuperview];
//                            }];
                            
                            //开始进行投标支付
                            [self bidPaymentImmediately];
                            
                        }else{
                            
                            
                            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
                        }
                        
                    }else{
                        
                        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];

                    }
                    


                }];

            }

        }];



}


-(void)bidPaymentImmediately{
    
//    id    [int]    是    标的id
//    money    [string]    是    投标金额
//    paypassword    [string]    是    支付密码
//    ecv_id    [int]        红包编号
//    interestrate_id    [int]        加息券编号
//    encryption    标的密码
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"id":_idStr,
                                                                               @"money":_money,
                                                                               @"paypassword":_passwordStr
                                                                               }];
    
    if (_hongbaoId.length!=0) {
        
        [dic setObject:_hongbaoId forKey:@"ecv_id"];
    }
    
    if (_jiaxiId.length!=0) {
        
        [dic setObject:_jiaxiId forKey:@"interestrate_id"];

    }
    
    if (_markpasswordStr.length!=0) {
        
        [dic setObject:_markpasswordStr forKey:@"encryption"];

    }
    
    [RTJNetWork asyncRequestWithURL:@"deals/dobid" params:dic method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        
        if (success) {
            
            if ([data[@"status"]integerValue]==1) {
                
                self.view.userInteractionEnabled = NO;

                [SVProgressHUD showSuccessWithStatus:@"投标成功"];
                RTJBidRecordsRootController *vc = [[RTJBidRecordsRootController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
                
            }else{
                
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"投标失败:%@",data[@"msg"]]];
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];

        }
    }];
    
}



-(void)chongzhiBtn{
    
    RTJChargeController *VC = [[RTJChargeController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
    
}

-(void)hongbaoBtn:(UIButton *)btn{
    
    NSInteger shuruMoney = [_money integerValue];
    
    if (shuruMoney==0) {
        
        [SVProgressHUD showErrorWithStatus:@"100元起投,请重新输入金额"];
        _isSurePay = YES;
        return;
        
    }
    
    if (btn.tag == 100) {
        
        
        if (shuruMoney<100) {
            
            [SVProgressHUD showErrorWithStatus:@"100元起投,请重新输入金额"];
            _isSurePay = YES;
            return;
        }
    }
    
    if (btn.tag == 100) {
        
        RTJHBJXController *vc =[[RTJHBJXController alloc]init];
        vc.title = @"红包";
        vc.delegate = self;
        vc.hongbaoArr = _hbList;
        vc.isUserCenter = NO;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        
        RTJJiaXiController *vc = [[RTJJiaXiController alloc]init];
        vc.jiaxiArr = _jxList;
         vc.title = @"加息券";
        vc.delegate = self;
        vc.isUserCenter = NO;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

-(void)hongBaoName:(NSString *)cardName money:(NSInteger)moeny cardId:(NSInteger)cardId min_money:(NSInteger)min_money{
    
    _hongbaoMin_money = min_money;
    _cardName = cardName;
    _cardId = cardId;
    _hongbao_money = moeny;
    
    NSInteger shuruMoney = [_money integerValue];
    
    if (shuruMoney < min_money) {
        
        [SVProgressHUD showErrorWithStatus:@"红包不可用"];
        
    }
    
    _hongbaoName = shuruMoney < min_money ? @"红包不可用":cardName;
    _hongbao =  shuruMoney< min_money ? 0:moeny;
    
    if (shuruMoney< min_money) {
        
        _hongbaoId = nil;
        
    }else{
        
        _hongbaoId = [NSString stringWithFormat:@"%ld",(long)cardId];
        
    }
    
    //预期收益
    //收益 = 投标金额*（预期年化*/100/12）*投资期限
    CGFloat rebate1 = [_rebateStr floatValue];//加息
    
    CGFloat rete = [_rateStr floatValue];
    
    CGFloat repay_time = [_timeStr floatValue];
    
    CGFloat shouyi = shuruMoney*((rete+_jiaxi+rebate1)/100/12)*repay_time;
    
    _yuqishouyi = [NSString stringWithFormat:@"%.2f",shouyi];
    
    //实际支付
    _payStr = [NSString stringWithFormat:@"%ld",shuruMoney-_hongbao];
    
    [self.tableView reloadData];
    
}

-(void)jiaxiName:(NSString *)cardName rate:(NSInteger)rate cardId:(NSInteger)cardId min_money:(NSInteger)min_money{
    
    NSInteger shuruMoney = [_money integerValue];
    
    _jiaxiName = cardName;
    _jiaxi = rate;
    _jiaxiId = [NSString stringWithFormat:@"%ld",(long)cardId];
    
    //预期收益
    //收益 = 投标金额*（预期年化*/100/12）*投资期限
    CGFloat rebate1 = [_rebateStr floatValue];//加息
    
    CGFloat rete = [_rateStr floatValue];
    
    CGFloat repay_time = [_timeStr floatValue];
    
    CGFloat shouyi = shuruMoney*((rete+_jiaxi+rebate1)/100/12)*repay_time;
    
    _yuqishouyi = [NSString stringWithFormat:@"%.2f",shouyi];
    
    //实际支付
    _payStr = [NSString stringWithFormat:@"%ld",shuruMoney-_hongbao];
    
    [self.tableView reloadData];
    
}

//-(void)hongBaoName:(NSString *)cardName money:(NSInteger)moeny cardId:(NSInteger)cardId minMoney:(NSInteger)minMoney{
//
//
//}
//
//-(void)JiaxiName:(NSString *)cardName rate:(NSInteger)rate cardId:(NSInteger)cardId minMoney:(NSInteger)minMoney{
//
//
//
//}

-(void)xieyi{
    
    RTJHTMLViewController *vc = [[RTJHTMLViewController alloc]init];
    vc.title = @"风险揭示书";
    vc.htmlStr = @"fengxianjiesishu";
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)xieyi2{
    
    RTJHTMLViewController *vc = [[RTJHTMLViewController alloc]init];
    vc.title = @"电子签章授权委托书";
    vc.htmlStr = @"dianziqianzhang";
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)xieyi1{
    
    RTJHTMLViewController *vc = [[RTJHTMLViewController alloc]init];
    vc.title = @"瑞泰金借款协议";
    vc.htmlStr = @"loan_agreement";
    [self.navigationController pushViewController:vc animated:YES];
    
}

@end
